<!--suppress HtmlDeprecatedAttribute -->
<template>
  <div class="wrapper">
    <PartAddGoodsDialog @update="dialogSuccess" v-model="dialogVisible" :type="dialogType" :id="dialogId"/>
    <div class="top">
      <div class="left">
        <span class="title">商品列表</span>
      </div>
      <div class="right">
        <el-button size="mini" :icon="buttonsFlag ? 'el-icon-arrow-right' : 'el-icon-arrow-left'"
                   @click="buttonBox"/>
        <el-button v-if="buttonsFlag" @click="handleClearSort" size="small"
                   :disabled="paginationDisabled">清除排序</el-button>
        <el-button v-if="buttonsFlag" @click="handleClearFilter" size="small"
                   :disabled="paginationDisabled">清除筛选</el-button>
        <el-button v-if="buttonsFlag" size="small" @click="handlePushGoodMore"
                   :disabled="pushGoodsDisabled">上架商品</el-button>
        <el-button v-if="buttonsFlag" size="small" @click="handlePullGoodMore"
                   :disabled="pullGoodsDisabled">下架商品</el-button>
        <el-button v-if="buttonsFlag" size="small" @click="handlePendingGoodMore"
                   :disabled="pushCheckDisabled">提交审核</el-button>
        <el-button v-if="buttonsFlag" size="small" @click="handleCancelPendingGoodMore"
                   :disabled="cancelCheckDisabled">撤销审核</el-button>
        <el-button @click="freshTable" size="small" icon="el-icon-refresh"
                   :disabled="paginationDisabled" :loading="paginationDisabled">刷新</el-button>
        <el-button @click="handleRemoveMore" type="danger" size="small" icon="el-icon-delete-solid"
                   :disabled="paginationDisabled ? '' : null">删除选择</el-button>
        <el-button @click="handleDialogAdd" type="primary" icon="el-icon-plus"
                   size="small">添加商品</el-button>
      </div>
    </div>
    <div class="table">
      <el-table ref="table" :data="tableData" style="width: 100%" height="449" max-height="600"
                v-loading='paginationDisabled' @selection-change="handleSelectionChange"
                :default-sort="tableSort" @sort-change="handleSortChange" :border="true"
                @filter-change="handleFilterChange">
        <el-table-column type="selection" align="center" width="50" fixed="left"/>
        <el-table-column prop="id" align="center" label="编号" columnKey="id" width="50"/>
        <el-table-column prop="name" align="center" label="名称" columnKey="name"
                         resizable sortable="custom" width="210" :show-overflow-tooltip="true"/>
        <el-table-column prop="goodCategoryName" align="center" label="类别" columnKey="category"
                         resizable :filters="filterColumns.category" sortable="custom" width="150"/>
        <el-table-column prop="groupName" align="center" label="分组" columnKey="group"
                         resizable :filters="filterColumns.group" sortable="custom" width="180"/>
        <el-table-column prop="sellPoint" align="center" label="卖点" columnKey="sellPoint"
                         resizable :filters="filterColumns.sellPoint" sortable="custom" width="90"
                         :show-overflow-tooltip="true"/>
        <el-table-column prop="freight" align="center" label="运费" columnKey="freight"
                         resizable sortable="custom" width="100"/>
        <el-table-column prop="createTime" align="center" label="创建时间" columnKey="createTime"
                         resizable sortable="custom" width="180"/>
        <el-table-column prop="state" align="center" label="状态" columnKey="state"
                         resizable :filters="[]" sortable="custom" width="100"/>
        <el-table-column prop="remark" align="center" label="备注" columnKey="remark"
                         resizable sortable="custom" width="100" :show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="center" fixed="right" resizable width="200">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDialogDetail(scope.row)">详情
            </el-button>
            <el-button type="text" size="small" @click="handleDialogEdit(scope.row)">修改
            </el-button>
            <el-button type="text" style="color: red" size="small" @click="handleRemove(scope.row)">移除
            </el-button>
            <el-button type="text" size="small" @click="handlePushGood(scope.row)"
                       v-if="scope.row.state === '未上架'">上架商品</el-button>
            <el-button type="text" size="small" @click="handlePullGood(scope.row)"
                       v-if="scope.row.state === '正常'">下架商品</el-button>
            <el-button type="text" size="small" @click="handlePendingGood(scope.row)"
                       v-if="scope.row.state === '待审核'">提交审核</el-button>
            <el-button type="text" size="small" @click="handleCancelPendingGood(scope.row)"
                       v-if="scope.row.state === '审核中'">撤销审核</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change='handleCurrentChange'
                     :page-size.sync='size' :total.sync="total" :current-page.sync="page" background
                     :disabled="paginationDisabled"
                     layout="sizes, total, jumper, prev, pager, next"/>
    </div>
  </div>
</template>

<script>
// noinspection JSUnusedGlobalSymbols
import PartAddGoodsDialog from '@pages/goods/part/pageGoodsList/PartAddGoodsDialog'
import {
  cancelGoodsCheckPending,
  pullGoods,
  pushGoods, pushGoodsCheckPending,
  queryGoodsByPageWrapperStore,
  queryStoreGoodTableFilter,
  removeGoodsByIds
} from '@/api/ApiGoods'
import { ResultCode } from '@/constants/constants'
import PageDTO from '@/api/entity/PageDTO'
import GoodsStoreQueryDTO from '@/api/entity/GoodsStoreQueryDTO'
import { GoodsState } from '@/constants/GoodsState'

export default {
  name: 'PageGoodsList',
  components: { PartAddGoodsDialog },
  data () {
    return {
      buttonsFlag: true,
      tableSort: {},
      dialogVisible: false,
      dialogType: 'add',
      dialogId: 0,
      tableData: [],
      selection: [],
      sortData: this.tableSort,
      filterData: {},
      loading: false,
      total: 0,
      size: 10,
      page: 1,
      filterLoading: true,
      filterColumns: {
        category: [],
        group: [],
        sellPoint: [],
        state: []
      }
    }
  },
  computed: {
    paginationDisabled () {
      return this.loading
    },
    selectIds () {
      const ids = []
      this.selection.forEach(item => {
        ids.push(item.id)
      })
      return ids
    },
    pushGoodsDisabled () {
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].state === GoodsState.STATE_NOT_ON) {
          return false
        }
      }
      return true
    },
    pullGoodsDisabled () {
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].state === GoodsState.STATE_NORMAL) {
          return false
        }
      }
      return true
    },
    pushCheckDisabled () {
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].state === GoodsState.STATE_CHECK_PENDING) {
          return false
        }
      }
      return true
    },
    cancelCheckDisabled () {
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].state === GoodsState.STATE_CHECKING) {
          return false
        }
      }
      return true
    }
  },
  methods: {
    buttonBox () {
      this.buttonsFlag = !this.buttonsFlag
    },
    /**
     * 打开添加商品对话框
     */
    handleDialogAdd () {
      this.dialogType = 'add'
      this.dialogId = 0
      this.dialogVisible = true
    },
    /**
     * 打开查看商品详情商品对话框
     * @param val 数据
     */
    handleDialogDetail (val) {
      this.dialogType = 'show'
      this.dialogId = val.id
      this.dialogVisible = true
    },
    /**
     * 打开编辑商品商品对话框
     * @param val 数据
     */
    handleDialogEdit (val) {
      this.dialogType = 'edit'
      this.dialogId = val.id
      this.dialogVisible = true
    },
    /**
     * 移除一个数据
     * @param val 数据
     */
    handleRemove (val) {
      this.$confirm('此操作将永久删除该商品信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = [val.id]
        removeGoodsByIds(ids, data => {
          if (data && data.code === ResultCode.OK) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.freshTable()
          }
        })
      }).catch(() => {
      })
    },
    /**
     * 清除排序
     */
    handleClearSort () {
      this.$refs['table'].clearSort()
      this.sortData = {}
      this.freshTable()
    },
    /**
     * 清除筛选
     */
    handleClearFilter () {
      this.$refs['table'].clearFilter()
      this.filterData = {}
      this.page = 1
      this.freshTable()
    },
    /**
     * 移除选择的多个数据
     */
    handleRemoveMore () {
      if (this.selectIds.length === 0) {
        this.$message.error('请先选择希望移除的商品')
        return
      }
      this.$confirm('此操作将永久删除这' + this.selectIds.length + '条商品信息，包括子商品信息及上传图片，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeGoodsByIds(this.selectIds, data => {
          if (data.code === ResultCode.OK) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.freshTable()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
     * 选择发生改变回调，同步数据
     * @param val 选择的数据，数组
     */
    handleSelectionChange (val) {
      this.selection = val
    },
    /**
     * 格式化时间格式
     * @param {Array} time 时间数组
     */
    formatTime (time) {
      for (let i = 1; i < time.length; i++) {
        time[i] = time[i] < 10 ? '0' + time[i] : '' + time[i]
      }
      return time[0] + '-' + time[1] + '-' + time[2] + ' ' + time[3] + ':' + time[4] + ':' + time[5]
    },
    dialogSuccess () {
      this.dialogVisible = false
      this.freshTable()
    },
    /**
     * 更新表格数据，size和page改变时都会调用
     */
    freshTable () {
      this.loading = true
      const pageDTO = PageDTO.instance()
      pageDTO.setSize(this.size)
      pageDTO.setCurrent(this.page)
      const condition = GoodsStoreQueryDTO.instance()
      // 排序
      if (this.sortData && this.sortData.prop && this.sortData.order) {
        if (this.sortData.order === 'descending') {
          condition.addSortDesc(this.sortData.prop)
        } else if (this.sortData.order === 'ascending') {
          condition.addSortAsc(this.sortData.prop)
        }
      }
      // 筛选
      Object.keys(this.filterData).forEach(key => {
        if (this.filterData[key].length > 0) {
          condition.addFilter(key, this.filterData[key])
        }
      })
      pageDTO.setCondition(condition)
      queryGoodsByPageWrapperStore(pageDTO, data => {
        if (data.code === ResultCode.OK) {
          this.tableData = data.object['records']
          this.tableData.forEach(item => {
            item.createTime = this.formatTime(item['createTime'])
          })
          this.total = data.object['total']
        }
      }, () => {
        this.loading = false
      })
    },
    /**
     * size改变更新数据
     */
    handleSizeChange () {
      this.page = 1
      this.freshTable()
    },
    /**
     * 排序改变监听，刷新页面
     * { column, prop, order }
     */
    handleSortChange (val) {
      this.sortData = val
      this.freshTable()
    },
    /**
     * 筛选改变监听
     */
    handleFilterChange (val) {
      Object.assign(this.filterData, val)
      this.page = 1
      this.freshTable()
    },
    /**
     * page改变更新数据
     */
    handleCurrentChange () {
      this.freshTable()
    },
    /**
     * 上架商品
     * @param val 数据
     */
    handlePushGood (val) {
      if (val && val.id) {
        const ids = [val.id]
        pushGoods(ids, data => {
          if (data && data.code === ResultCode.OK) {
            this.$message.success('商品上架成功')
            this.freshTable()
          }
        })
      } else {
        this.$message.error('本地参数错误')
      }
    },
    /**
     * 下架商品
     * @param val 数据
     */
    handlePullGood (val) {
      if (val && val.id) {
        const ids = [val.id]
        pullGoods(ids, data => {
          if (data && data.code === ResultCode.OK) {
            this.$message.success('商品下架成功')
            this.freshTable()
          }
        })
      } else {
        this.$message.error('本地参数错误')
      }
    },
    /**
     * 提交商品审核
     * @param val 数据
     */
    handlePendingGood (val) {
      if (val && val.id) {
        const ids = [val.id]
        pushGoodsCheckPending(ids, data => {
          if (data && data.code === ResultCode.OK) {
            this.$message.success('商品提交审核成功')
            this.freshTable()
          }
        })
      } else {
        this.$message.error('本地参数错误')
      }
    },
    /**
     * 取消审核中的商品数据
     * @param val 数据
     */
    handleCancelPendingGood (val) {
      if (val && val.id) {
        const ids = [val.id]
        cancelGoodsCheckPending(ids, data => {
          if (data && data.code === ResultCode.OK) {
            this.$message.success('商品取消审核申请成功')
            this.freshTable()
          }
        })
      } else {
        this.$message.error('本地参数错误')
      }
    },
    /**
     * 上架商品
     */
    handlePushGoodMore () {
      if (this.selectIds.length === 0) {
        this.$message.error('请先选择希望上架的商品')
        return
      }
      pushGoods(this.selectIds, data => {
        if (data && data.code === ResultCode.OK) {
          this.$message.success('上架商品成功')
          this.freshTable()
        }
      })
    },
    /**
     * 下架商品
     */
    handlePullGoodMore () {
      if (this.selectIds.length === 0) {
        this.$message.error('请先选择希望下架架的商品')
        return
      }
      pullGoods(this.selectIds, data => {
        if (data && data.code === ResultCode.OK) {
          this.$message.success('下架商品成功')
          this.freshTable()
        }
      })
    },
    /**
     * 提交商品审核
     */
    handlePendingGoodMore () {
      if (this.selectIds.length === 0) {
        this.$message.error('请先选择希望提交审核的商品')
        return
      }
      pushGoodsCheckPending(this.selectIds, data => {
        if (data && data.code === ResultCode.OK) {
          this.$message.success('商品提交审核成功')
          this.freshTable()
        }
      })
    },
    /**
     * 取消审核中的商品数据
     */
    handleCancelPendingGoodMore () {
      if (this.selectIds.length === 0) {
        this.$message.error('请先选择希望取消审核的商品')
        return
      }
      cancelGoodsCheckPending(this.selectIds, data => {
        if (data && data.code === ResultCode.OK) {
          this.$message.success('商品取消审核成功')
          this.freshTable()
        }
      })
    }
  },
  /**
     * 初始化更新数据
     */
  mounted () {
    this.freshTable()
    // 查询本店铺商品用于筛选的待筛选信息
    queryStoreGoodTableFilter(data => {
      const columns = data.object
      if (columns) {
        if (columns.category) {
          columns.category.forEach(item => {
            item.text = item.name
            item.value = item.id
          })
        }

        if (columns.group) {
          columns.group.forEach(item => {
            item.text = item.name
            item.value = item.id
          })
        }

        const newSellPoint = []
        if (columns.sellPoint) {
          columns.sellPoint.forEach(item => {
            newSellPoint.push({
              text: item,
              value: item
            })
          })
        }
        columns.sellPoint = newSellPoint

        const newFreight = []
        if (columns.freight) {
          columns.freight.forEach(item => {
            newFreight.push({
              text: item,
              value: item
            })
          })
        }
        columns.freight = newFreight
      }
      this.filterColumns = columns
    }, () => {
      this.filterColumns = false
    })
  }
}
</script>

<style lang="scss" scoped>

  .wrapper {

    .top {

      width: 100%;
      height: 50px;
      border-bottom: 1px solid #999999;
      margin-bottom: 8px;

      .left {
        display: inline-block;
        width: 20%;
        text-align: left;
      }

      .right {
        display: inline-block;
        width: 80%;
        text-align: right;
      }

    }

    .table {
      margin: 16px 0;
      text-align: center;

      .pagination {
        margin: 20px auto;
      }
    }

  }

</style>
